import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

// 定义 qiankun 的 props 类型
export type QiankunProps = {
  container?: HTMLElement | ShadowRoot;
};

let root: ReactDOM.Root | null = null;

function render(props: QiankunProps = {}) {
  const { container } = props;
  const rootElement = container
    ? container.querySelector('#root')
    : document.getElementById('root');

  if (!rootElement) {
    console.error('Root element not found');
    return;
  }

  root = ReactDOM.createRoot(rootElement);
  root.render(<App />);
}

// 独立运行时
if (!(window as any).__POWERED_BY_QIANKUN__) {
  render();
}

/**
 * qiankun 生命周期钩子（必须导出）
 */
export async function bootstrap() {
  console.log('[Webpack TS 子应用] bootstraped');
}

export async function mount(props: QiankunProps) {
  console.log('[Webpack TS 子应用] mounted', props);
  render(props);
}

export async function unmount(props: QiankunProps) {
  console.log('[Webpack TS 子应用] unmounted', props);
  if (root) {
    root.unmount();
    root = null;
  }
}